package com.kurumi.medical.interceptor;

import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.kurumi.medical.pojo.User;
import com.kurumi.medical.util.CookieUtils;
import com.kurumi.medical.util.HttpClientUtil;
import com.kurumi.medical.util.PropsUtil;
/**
 * 安全认证处理
 * @author lyh
 *
 */
public class SecurityHandlerInterceptor implements HandlerInterceptor {

	Properties pro = PropsUtil.loadProps("application.properties");
	String remote_login_url = pro.getProperty("login.check.url");
	
	//在处理器适配器执行前调用 为各种处理器适配 通俗的讲意思就是说在执行controller的方法之前执行
	//返回true或者是false，true代表的是执行后面的逻辑，即执行后面的处理器或者拦截器
	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		// TODO Auto-generated method stub
//		if(response.getStatus() == HttpStatus.NOT_FOUND.value()){
//			return true;
//		}
//		Subject subject = SecurityUtils.getSubject();
//		Session session = subject.getSession();
//		User users = (User) request.getSession().getAttribute("user");
//		Cookie[] cookies = request.getCookies();
//			
//		if (null != cookies) {
//			for (Cookie c : cookies) {
//				String cookieName = c.getName();
//				String cookieValue = c.getValue();
//				if (cookieName.contains("TT_TOKEN") && StringUtils.isNotBlank(cookieValue) && null != users) {
//					//String loginName = cookieValue;
//					CookieUtils.setCookie(request, response, "TT_TOKEN", cookieValue, 1800);
//					String userName = CookieUtils.getCookieValue(request, "userName");
//					String officeCode = CookieUtils.getCookieValue(request, "officeCode");
//					String officeName = CookieUtils.getCookieValue(request, "officeName");
//					CookieUtils.setCookie(request, response, "userName", userName, 1800);
//					CookieUtils.setCookie(request, response, "officeCode", officeCode, 1800);
//					CookieUtils.setCookie(request, response, "officeName", officeName, 1800);
//					session.setAttribute("user", users);
//					session.setTimeout(1800000);
//					return true;
////					}
//				}
//			}
//		} 
//		
//		//获取contextPath
//		String contextPath = request.getContextPath();
//		int index = contextPath.lastIndexOf("/");
//		contextPath = contextPath.substring(index+1);
//		
//		if (null != cookies) {
//			for (Cookie c : cookies) {
//				String cookieName = c.getName();
//				String cookieValue = c.getValue();
//				if (cookieName.contains("TT_TOKEN") && StringUtils.isNotBlank(cookieValue)) {
//					String loginName = cookieValue;
//					
//					//远程调用sso系统
//					Map<String, String> params = new HashMap<String, String>();
//					params.put("username", loginName);
//					params.put("contextPath", contextPath);
//					// 远程调用sso登录系统
//					String userJson = HttpClientUtil.doPost(remote_login_url, params);
//
//					JSONObject userMap = JSONObject.parseObject(userJson);
//
//					if ((Boolean) userMap.get("isSuccess")) {
////						Subject subject = SecurityUtils.getSubject();
////						Session session = subject.getSession();
//						session.setAttribute("contextPath", contextPath);
//						UsernamePasswordToken token = new UsernamePasswordToken(loginName, (String)userMap.get("password"));
//						subject.login(token);
//						String name = userMap.get("name")!=null&&userMap.get("name")!=""?(String)userMap.get("name"):"";
//						String officeCode = userMap.get("officeCode")!=null&&userMap.get("officeCode")!=""?(String)userMap.get("officeCode"):"";
//						String officeName = userMap.get("officeName")!=null&&userMap.get("officeName")!=""?(String)userMap.get("officeName"):"";
//						User user = new User();
//						user.setId((String)userMap.get("id"));
//						user.setLoginName(loginName);
//						user.setPassword((String)userMap.get("password"));
//						user.setContextPath(contextPath);
//						user.setMedicalMainstayId((String)userMap.get("medicalMainstayId"));
//						user.setName(name);
//						session.setAttribute("user", user);
//						session.setTimeout(1800000);
//						c.setMaxAge(1800);
//						CookieUtils.setCookie(request, response, "userName", name, 1800);
//						CookieUtils.setCookie(request, response, "TT_TOKEN", loginName, 1800);
//						CookieUtils.setCookie(request, response, "officeCode", officeCode, 1800);
//						CookieUtils.setCookie(request, response, "officeName", officeName, 1800);
//						return true;
//					}
//					
//					response.sendRedirect(request.getContextPath() + "/user/loginForm");
//					return false;
//				}
//			}
//		} 
//		response.sendRedirect(request.getContextPath() + "/user/loginForm");
//		return false;
		return true;
	}

	//在执行完适配的调用方法后，生成视图之前执行，官方是这样解析的：
	// but before the DispatcherServlet renders the view.
	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		// TODO Auto-generated method stub

	}

	//在所有的操作以后执行
	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		// TODO Auto-generated method stub

	}

}
